<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span class="header-title">用户管理</span>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline class="search-form">
      <el-form-item label="用户名：">
        <el-input v-model="searchKeyword" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 用户列表 -->
    <el-table :data="userList" class="user-table" border stripe highlight-current-row>
      <el-table-column prop="username" label="用户名" align="center" min-width="120" show-overflow-tooltip />
      <el-table-column prop="age" label="年龄" align="center" min-width="100" />
      <el-table-column prop="school" label="学校" align="center" min-width="180" show-overflow-tooltip />
      <el-table-column label="操作" align="center" min-width="100">
        <template #default="{ row }">
          <el-button 
            :icon="Edit" 
            circle plain 
            type="primary" 
            @click.stop="handleEdit(row)" 
          />
          <el-button 
            :icon="Delete" 
            circle plain 
            type="danger" 
            @click.stop="handleDelete(row)" 
          />
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无用户数据" />
      </template>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 50]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      class="pagination-bar"
    />

    <!-- 编辑用户弹框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑用户" 
      :close-on-click-modal="false"
      class="user-dialog"
    >
      <el-form 
        :model="editForm" 
        label-width="80px"
        :rules="editRules"
        ref="editFormRef"
        class="dialog-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="editForm.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="学校" prop="school">
          <el-input v-model="editForm.school" placeholder="请输入学校" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">保存修改</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { Search, Delete, Edit, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getUserList, deleteUser, updateUserInfoService as updateUser } from '@/api/user.js'
import { ElMessage, ElMessageBox} from 'element-plus';
const router = useRouter()

// 表格数据
const userList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 编辑弹框相关
const editDialogVisible = ref(false)
const editForm = ref({
  id: null,
  username: '',
  age: null,
  school: ''
})
const editRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  school: [{ required: true, message: '请输入学校', trigger: 'blur' }]
})
const editFormRef = ref(null)

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      username: searchKeyword.value ? searchKeyword.value : null
    })
    userList.value = res.data.items
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取用户失败，请重试')
  }
}

// 处理编辑按钮点击
const handleEdit = (row) => {
  editDialogVisible.value = true
  // 复制用户数据到编辑表单
  editForm.value = {
    id: row.id,
    username: row.username,
    age: row.age,
    school: row.school
  }
}

// 处理用户修改
const handleUpdate = async () => {
  try {
    // 表单验证
    await editFormRef.value.validate()
    // 调用修改接口
    const res = await updateUser(editForm.value)
    ElMessage.success('用户信息修改成功')
    editDialogVisible.value = false
    fetchUserList() // 刷新列表
  } catch (error) {
    ElMessage.error('修改失败，请检查输入内容')
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除用户，确认吗？',
      '警告',
      { type: 'warning' }
    )
    await deleteUser(row.id)
    ElMessage.success('删除成功！')
    await fetchUserList()
  } catch (error) {
    ElMessage.info('已取消删除')
  }
}

// 分页/搜索事件
const handlePageChange = (val) => {
  currentPage.value = val
  fetchUserList()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchUserList()
}
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}
const handleReset = () => {
  searchKeyword.value = ''
  fetchUserList()
}

onMounted(() => {
  fetchUserList()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
  background: #f7f8fa;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
  padding-bottom: 30px;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0 0 0;

    .header-title {
      font-size: 22px;
      font-weight: 600;
      color: #222;
      letter-spacing: 1px;
    }
  }
}

.search-form {
  margin: 20px 0 0 0;
  .el-form-item {
    margin-right: 20px;
  }
}

.user-table {
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  margin-top: 18px;
  .el-table__header th {
    background: #f2f3f5;
    color: #333;
    font-weight: 500;
  }
  .el-table__row {
    transition: background 0.2s;
  }
  .el-table__row:hover {
    background: #f5f7fa;
  }
}

.pagination-bar {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.el-select {
  --el-select-width: 220px;
}

.user-dialog {
  border-radius: 12px;
  .el-dialog__header {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
  .dialog-form {
    margin-top: 10px;
    .el-form-item {
      margin-bottom: 18px;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>